package cn.ycq.im.http;

import cn.ycq.im.http.exception.HttpException;
import cn.ycq.im.http.exception.HttpResourceNotFound;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

public class DefaultHttpRequestHandler extends SimpleChannelInboundHandler<HttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpRequest httpRequest) throws Exception {
        try {
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK);
            Routers.DEFAULT.findHandleAndInvoke(httpRequest,response);
            channelHandlerContext.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }catch (HttpException e){
            if(e instanceof HttpResourceNotFound){
                DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);

                ByteBuf byteBuf = Unpooled.copiedBuffer("资源没有找到".getBytes());
                defaultFullHttpResponse.content().writeBytes(byteBuf);
                channelHandlerContext.writeAndFlush(defaultFullHttpResponse).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}
